package com.bss;

import java.io.File;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.logging.Logger;

public class BackupManager {

	static Logger logger = Logger.getAnonymousLogger();

	private static final String PASSWORD = "nopass";

	public void backup(String command, String user, String password, String database, String backupName, String location)
			throws Exception {

		BackupManager.logger.info("Backup started...");

		String target = location + File.separatorChar + backupName + "-" + getDate() + ".txt";

		String exec = command + " -u " + user + " --password=" + password + " --lock-tables=FALSE -r " + target + " " + database;

		Process pp = Runtime.getRuntime().exec(exec);
		pp.waitFor();

		BackupManager.logger.info("Backup completed... Saved at " + target);
		System.exit(pp.exitValue());

	}

	public static String getDate() {
		Calendar c = new GregorianCalendar();
		return c.get(Calendar.DATE) + "-" + (c.get(Calendar.MONTH) + 1) + "-" + c.get(Calendar.YEAR);
	}

	public static void main(String[] args) throws Exception {
		if (args.length < 6) {
			System.out.println("Usage java " + BackupManager.class.getName()
					+ " command user passowrd database backupName location");
			System.exit(1);

		}

		String password = BackupManager.PASSWORD;
		if (!"xxx".equalsIgnoreCase(args[2])) {
			password = args[2];
		}
		new BackupManager().backup(args[0], args[1], password, args[3], args[4], args[5]);

	}

}
